package com.zb.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import com.zb.dao.SecurityDao;
import com.zb.security.pojo.Sec_User;

/**
 * 
 * 
 * 作者: zhoubang 
 * 日期：2015年8月25日 下午5:33:13
 */
@Repository(value = "securityDaoImpl")
public class SecurityDaoImpl implements SecurityDao {

    @Resource(name = "sqlSession")
    // 也可以直接使用@Autowired
    private SqlSessionTemplate sqlSession;

    @Override
    public Sec_User getUserByAccount(String userAccount) {
        Sec_User user = (Sec_User) sqlSession.selectOne("getUserByName",
                userAccount);
        return user;
    }

    @Override
    public String getUserRolesByAccount(String userAccount) {
        String roles = (String) sqlSession.selectOne("getUserRolesByAccount",
                userAccount);
        return roles;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Map<String, String>> getResourceAndThisRoles() {
        List<Map<String, String>> resRolesList = (List<Map<String, String>>) sqlSession
                .selectList("getResourceAndThisRoles");
        return resRolesList;
    }

    @Override
    public int register(Sec_User sec_User) {
        sqlSession.insert("register", sec_User);
        return sec_User.getId();
    }

    @Override
    public int updateUserRole(int userId, List<Integer> roles) {

        for (Integer roleId : roles) {
            Map<String, Object> m = new HashMap<String, Object>();
            m.put("userId", userId);
            m.put("roleId", roleId);

            sqlSession.insert("updateUserRole", m);
        }
        return 1;
    }

    @Override
    public boolean checkAccount(String account) {
        Sec_User user = (Sec_User) sqlSession
                .selectOne("checkAccount", account);
        return user == null ? false : true;
    }

    @Override
    public Sec_User login(String account, String password) {
        Map<String, Object> m = new HashMap<String, Object>();
        m.put("account", account);
        m.put("password", password);
        Sec_User sec_User = (Sec_User) sqlSession.selectOne("login", m);
        return sec_User;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Map<String, String>> getAllSecUser() {
        List<Map<String, String>> userList = (List<Map<String, String>>) sqlSession
                .selectList("getAllSecUser");
        return userList;
    }
}
